package com.ushine.web.security.handler;


import com.ushine.web.component.exception.LoginErrorEnum;
import com.ushine.web.security.response.SecurityResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: yls
 * @Date: 2021/08/17 21:39
 * @Description: 登录失败
 * @Version 1.0
 */
@Component
public class FightAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Resource
    SecurityResponse securityResponse;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //Security内置的异常处理
        if (e instanceof LockedException) {
            securityResponse.getResponse(response, LoginErrorEnum.USER_ACCOUNT_LOCKED);
        } else if (e instanceof CredentialsExpiredException) {
            securityResponse.getResponse(response, LoginErrorEnum.USER_CREDENTIALS_EXPIRED);
        } else if (e instanceof AccountExpiredException) {
            securityResponse.getResponse(response, LoginErrorEnum.USER_ACCOUNT_EXPIRED);
        } else if (e instanceof DisabledException) {
            securityResponse.getResponse(response, LoginErrorEnum.USER_ACCOUNT_DISABLE);
        } else if (e instanceof BadCredentialsException) {
            securityResponse.getResponse(response, LoginErrorEnum.USER_CREDENTIALS_ERROR);
        } else {
            securityResponse.getResponse(response, LoginErrorEnum.USER_LOGIN_FAILED);
        }
    }

}
